package com.ysjweb.dish.Service;

import com.ysjweb.dish.Service.impl.LoadMysqlImpl;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.Metadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.sql.*;

@Slf4j
@Component
public class LoadMysql implements LoadMysqlImpl {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/DishData";
    private static final String USER = "root";
    private static final String PASS = "49463-1123";

    @Override
    public List<Document> LoadMysql( Integer Limit) {
        List<Document> allDocuments = new ArrayList<>();
        int offset = 0;

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            while (true) {
                List<Document> batch = loadBatch(conn, Limit, offset);
                if (batch.isEmpty()) break;

                allDocuments.addAll(batch);
                offset += Limit;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return allDocuments;
    }

    private List<Document> loadBatch(Connection conn, int limit, int offset) {
        List<Document> batch = new ArrayList<>();
        String sql = "SELECT id, CONCAT('食材',element,'\n\n做法',process)AS content FROM menu ORDER BY id LIMIT ? OFFSET ?";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, limit);
            stmt.setInt(2, offset);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Metadata metadata = new Metadata();
                    metadata.put("id", rs.getString("id"));
//                    metadata.put("process", rs.getString("process"));
//                    metadata.put("element", rs.getString("element"));
                    Document doc=Document.from(
                            rs.getString("content"),
                            metadata
                    );
                    batch.add(doc);
                }
            }
        } catch (SQLException e) {
            log.info("第{}次装配失败",offset/limit);
            throw new RuntimeException(e);
        }
        return batch;
    }
}
